package com.hjl.cn.service;

import com.hjl.cn.config.wxconfig.WxPayConfig;
import com.hjl.cn.utils.HttpClientUtils;
import com.hjl.cn.utils.UuidUtils;
import com.hjl.cn.utils.WxPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @author jialin
 * @createTime 2020-09-28
 */
@Service
public class WxPayService {

    @Autowired
    private WxPayConfig wxPayConfig;

    public String unifiedOrder() throws Exception {
        //生成有序map
        SortedMap<String, String> param = new TreeMap<>();
        param.put("appid", wxPayConfig.getAppid());
        param.put("mch_id", wxPayConfig.getMchid());
        param.put("nonce_str", UuidUtils.createNonceStr());
        param.put("body", "星空");
        int num = Math.abs(new Random().nextInt());
        param.put("out_trade_no", String.valueOf(num));
        param.put("total_fee", "1");
        param.put("spbill_create_ip", "192.168.160.1");
        param.put("notify_url", wxPayConfig.getNotifyUrl());
        param.put("trade_type", "NATIVE");
        param.put("product_id", "202161015");
        param.put("sign", WxPayUtils.generateSignature(param, wxPayConfig.getKey()));
        String paramXML = WxPayUtils.mapToXml(param);
        String result = HttpClientUtils.doPost(wxPayConfig.getUnifiedUrl(), paramXML, 5000);
        Map<String, String> mapResult = WxPayUtils.xmlToMap(result);
        String codeUrl = mapResult.get("code_url");
        if (StringUtils.isEmpty(codeUrl)) {
            throw new RuntimeException("error");
        }
        return codeUrl;
    }
}
